//
//  JPStatusListViewModel.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/23.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage

class JPStatusListViewModel: NSObject {

    lazy var statusList: [JPStatusViewModel] = [JPStatusViewModel]()
    
    static let sharedStatusList = JPStatusListViewModel()
    
    func loadData(isPullUp: Bool, callBack: @escaping (Bool, String)->()) {
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        
        if isPullUp {
            maxId = statusList.last?.status?.id ?? 0
            if maxId > 0 {
                 maxId -= 1
            }
        }else {
            sinceId = statusList.first?.status?.id ?? 0
        }
        
        JPStatusDAL.loadData(sinceId: sinceId, maxId: maxId) { (statusArr) in
            
            let message = statusArr.count > 0 ? "加载到\(statusArr.count)条数据":"没有加载到数据"
            let statuses = NSArray.yy_modelArray(with: JPStatusModel.self, json: statusArr) as! [JPStatusModel]
            
            var tempArrM = [JPStatusViewModel]()
            
            let group = DispatchGroup()
            
            for value in statuses {
                let statusViewModel = JPStatusViewModel(status: value)
                
                tempArrM.append(statusViewModel)
                
                if value.pic_urls?.count == 1 {
                    
                    if let url = value.pic_urls?.first?.thumbnail_pic {
                        
                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string: url), options: [], progress: nil, completed: { (image, error, _, _, url) in
                            
                            group.leave()
                        })
                    }
                }
                
                if value.retweeted_status?.pic_urls?.count == 1 {
                    
                    if let url = value.retweeted_status?.pic_urls?.first?.thumbnail_pic {
                        
                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string: url), options: [], progress: nil, completed: { (image,error, _, _, url) in
                            
                            group.leave()
                        })
                    }
                }
            }
            
            if isPullUp {
                self.statusList.append(contentsOf: tempArrM)
            }else {
                self.statusList.insert(contentsOf: tempArrM, at: 0)
            }
            
            group.notify(queue: DispatchQueue.main, execute: {
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
                    
                    callBack(true, message)
                })
                
                
            })
        }
        
    }

}
